<!-- src/views/component/UserForm.vue -->
<script setup>
import { ref, defineProps, defineEmits, watch } from 'vue'

// 定义组件属性
const props = defineProps({
  modelValue: {
    type: Object,
    required: true
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

// 定义事件发射
const emit = defineEmits(['update:modelValue', 'submit', 'cancel'])

// 表单引用
const ruleFormRef = ref(null)

// 表单数据
const userForm = ref({ ...props.modelValue })

// 表单验证规则
const rules = ref({
  name: [
    { required: true, message: '请输入员工名称', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请输入角色', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  contactInfo: [
    { required: true, message: '请输入联系方式', trigger: 'blur' }
  ]
})

// 监听props变化更新表单数据
watch(() => props.modelValue, (newVal) => {
  userForm.value = { ...newVal }
}, { deep: true })

// 提交表单
const submitForm = async () => {
  if (!ruleFormRef.value) return;

  try {
    await ruleFormRef.value.validate() // 表单验证
    emit('submit', userForm.value)
  } catch (err) {
    // 验证失败不执行任何操作
  }
};

// 取消操作
const cancelForm = () => {
  emit('cancel')
}

// 重置表单
const resetForm = () => {
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields()
  }
}

// 暴露方法给父组件
defineExpose({
  resetForm
})

</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="userForm"
    :rules="rules"
    label-width="100px"
  >
    <el-form-item prop="id" label="员工编号">
      <el-input v-model="userForm.id" placeholder="请输入员工编号" :disabled="isEdit" />
    </el-form-item>
    <el-form-item prop="name" label="员工名称">
      <el-input v-model="userForm.name" placeholder="请输入员工名称" />
    </el-form-item>
    <el-form-item prop="role" label="角色">
      <el-input v-model="userForm.role" placeholder="请输入角色" />
    </el-form-item>
    <el-form-item prop="gender" label="性别">
      <el-select v-model="userForm.gender" placeholder="请选择性别">
        <el-option label="男" value="1" />
        <el-option label="女" value="2" />
      </el-select>
    </el-form-item>
    <el-form-item prop="contactInfo" label="联系方式">
      <el-input type="textarea" v-model="userForm.contactInfo" placeholder="请输入联系方式" />
    </el-form-item>
    <el-form-item label="是否有效">
      <el-switch
        v-model="userForm.whether"
        :active-value="1"
        :inactive-value="0"
        active-text="是"
        inactive-text="否"
      />
    </el-form-item>
  </el-form>
  <div class="dialog-footer">
    <el-button @click="cancelForm">取消</el-button>
    <el-button type="primary" @click="submitForm">提交</el-button>
  </div>
</template>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 20px 0;
}
</style>